package com.luochq.netty.netty03;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyNettyServer {
    public static void main(String[] args) {
        // 创建服务器启动器
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 主 boss accept
        EventLoopGroup bossEventLoopGroup = new NioEventLoopGroup(1);
        // 从 worker read write
        EventLoopGroup workerEventLoopGroup = new NioEventLoopGroup(3);
        // defaultEventLoop - 普通线程 用于处理非IO操作
        EventLoopGroup defaultEventLoopGroup = new DefaultEventLoop();
        // 设置channel -- NioServerSocketChannel
        serverBootstrap.channel(NioServerSocketChannel.class);
        // 多线程
        serverBootstrap.group(bossEventLoopGroup, workerEventLoopGroup);

        serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                nioSocketChannel.pipeline().addLast(defaultEventLoopGroup, new StringDecoder());
                nioSocketChannel.pipeline().addLast(defaultEventLoopGroup, new ChannelInboundHandlerAdapter() {
                    @Override
                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                        log.debug("{}", msg);
                    }
                });
            }
        });

        serverBootstrap.bind(8808);
    }
}
